package com.dwusoft.banks.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import utils.Constants;

import com.dwusoft.banks.model.TransInput;
import com.dwusoft.banks.tradeBank.common.utils.FtpUtil;

@Controller
@RequestMapping("/notify")
public class NotifyController {

	private final static Logger logger = LoggerFactory.getLogger(NotifyController.class);
	protected static String ftpConnectionString = "197.3.133.201,21,tbank,tbank123";// FTP；端口好；用户名；密码
	
	@RequestMapping(value = "{action}", method = RequestMethod.GET)
	public void p2pHome(ModelMap modelMap, HttpServletRequest request) {
		String base = request.getContextPath();
		String fullPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + base;
		logger.info("访问： " + fullPath);
		modelMap.addAttribute("base", base);
	}

	@RequestMapping(value = "/fileGenerateNotify", method = RequestMethod.POST)
	public String execute(@RequestParam(value = "attachment") MultipartFile attachment, TransInput transInput, ModelMap model, HttpServletRequest request) {
		logger.info(transInput.toString());
		

		String fileName = attachment.getOriginalFilename();
		String filePath = "/batch_handle_520/TBANK/EMCS/SECU/Request/uploadTest";
		
		// 1.上传文件至FTP
		logger.info("================step 1  上传文件至FTP=================");
		String uploadFileName = uploadFileToServer(attachment, request);
		uploadLocalFileToFtp(uploadFileName, fileName);

		// 2.生成报文
		logger.info("================step 2  生成报文=================");
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("secuNo", transInput.getSecuNo());
		paramMap.put("fileName", fileName);
		paramMap.put("filePath", filePath);

		logger.info("报文参数：" + paramMap);

		logger.info("================step 3  返回前台，调整资金托管平台 =================");
		model.addAttribute("paraMap", paramMap);
		
		logger.info("ServerPort:" + request.getServerPort());
		if (Constants.INTERNAL_PORT == request.getServerPort()) {
			model.addAttribute("actionURL", Constants.NET_TRADE_PLATFORM_INTERNAL_URL + request.getServletPath());
		} else if (Constants.EXTERNAL_PORT == request.getServerPort()) {
			model.addAttribute("actionURL", Constants.NET_TRADE_PLATFORM_EXTERNAL_URL + request.getServletPath());
		} else {
			model.addAttribute("actionURL", Constants.NET_TRADE_PLATFORM_URL + request.getServletPath());
		}
		logger.info("actionURL:" + (String)model.get("actionURL"));
		return "redirectProd";
	}
	
	@RequestMapping(value = "/accChangeNotify", method = RequestMethod.POST)
	public String execute(TransInput transInput, ModelMap model, HttpServletRequest request) {
		
		Map<String, String[]> params = request.getParameterMap();
		Map<String, String> paramMap = new HashMap<String, String>();
		Set<String> s = params.keySet();
		
		paramMap.put(Constants.PARAM_CUST_NO, transInput.getSecuNo());
		paramMap.put(Constants.PARAM_TRANSCODE, transInput.getTransCode());
		for(String key : s){
			paramMap.put(key, params.get(key)[0]);
		}
		
		model.addAttribute("paraMap", paramMap);

		logger.info("ServerPort:" + request.getServerPort());
		if (Constants.INTERNAL_PORT == request.getServerPort()) {
			model.addAttribute("actionURL", Constants.NET_TRADE_PLATFORM_INTERNAL_URL + "/product/accChangeNotify.json");
		} else if (Constants.EXTERNAL_PORT == request.getServerPort()) {
			model.addAttribute("actionURL", Constants.NET_TRADE_PLATFORM_EXTERNAL_URL + "/product/accChangeNotify.json");
		} else {
			model.addAttribute("actionURL", Constants.NET_TRADE_PLATFORM_URL + "/product/accChangeNotify.json");
		}
		logger.info("actionURL:" + (String)model.get("actionURL"));
		return "redirectProd";
	}

	/**
	 * 上传文件至服务器
	 * @param attachment
	 * @param request
	 * @return
	 */
	private String uploadFileToServer(MultipartFile attachment, HttpServletRequest request) {
		// 此为weblogic上的目录
//		String path = request.getSession().getServletContext().getRealPath("/upload");
		String path = "/weblogic/netTradeGate/upload";
		String fileName = attachment.getOriginalFilename();
		File targetFile = new File(path, fileName);
		try {
			attachment.transferTo(targetFile);
			logger.info("文件上传至服务器成功，" + targetFile.getAbsolutePath());
			return targetFile.getAbsolutePath();
		} catch (Exception e) {
			logger.error("文件上传至服务器失败", e);
		}
		return null;
	}
	
	/**
	 * 从服务器发送文件至FTP
	 * @param uploadFileName 服务器上文件的全路径
	 * @param fileName 上传文件的文件名
	 * @return
	 */
	private boolean uploadLocalFileToFtp(String uploadFileName, String fileName) {
		boolean returnResult = false;

		FTPClient ftpClient = null;
		FtpUtil ftpUtil = new FtpUtil(ftpConnectionString);

		FileInputStream inputStream = null;
		try {
			logger.info("准备将从P2P平台下载的文件上传至托管平台FTP");

			// 连接FTP服务器
			ftpClient = ftpUtil.connectServer();
			if (ftpClient == null) {
				logger.error("连接到FTP服务器失败");
				throw new Exception("连接到FTP服务器失败");
			}

			String uploadDirectory = "/batch_handle_520/TBANK/EMCS/SECU/Request/uploadTest";//当前为写死的固定路径
			logger.info("需要将文件上传到托管平台FTP上的目录=" + uploadDirectory);
			if (ftpClient.changeWorkingDirectory(uploadDirectory)) {
				logger.info("目录=" + uploadDirectory + "已存在");
			} else {
				logger.info("目录=" + uploadDirectory + "尚不存在，需要创建");
				if (FtpUtil.makeDirectory(ftpClient, uploadDirectory)) {
					logger.info("目录=" + uploadDirectory + "创建成功");
				}
			}
			// 最终尝试切换目录
			if (!ftpClient.changeWorkingDirectory(uploadDirectory)) {
				logger.error("切换到FTP最终目录下失败");
				returnResult = false;
			}

			// 上传文件
			inputStream = new FileInputStream(uploadFileName);
			if (ftpClient.storeFile(fileName, inputStream)) {
				returnResult = true;
				logger.info("FTP文件上传成功");
			} else {
				logger.error("FTP文件上传失败");
				returnResult = false;
			}
		} catch (Exception ex) {
			logger.error("将本地文件上传到FTP时失败，原因=", ex);
			returnResult = false;
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
				}
			}

			if (ftpClient != null) {
				ftpUtil.closeConnect(ftpClient);
			}
		}
		return returnResult;
	}
	
}
